package com.bndg.browser

import android.graphics.Bitmap
import android.graphics.Color
import android.util.Log
import android.view.KeyEvent
import android.view.ViewGroup
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import com.blankj.utilcode.util.RegexUtils
import com.bndg.browser.widget.WebLayout
import com.hjq.base.BaseActivity
import com.just.agentweb.AgentWeb
import com.just.agentweb.DefaultWebClient
import com.just.agentweb.WebChromeClient
import com.just.agentweb.WebViewClient


class MainBrowserActivity : BaseActivity() {
    private var currentUrl: String = "https://cn.bing.com/"
    var mAgentWeb: AgentWeb? = null
    private val mToolbar: Toolbar? by lazy { findViewById(R.id.toolbar) }
    private val mTitleTextView: TextView? by lazy { findViewById(R.id.toolbar_title) }
    private val container: ViewGroup? by lazy { findViewById(R.id.container) }

    private val mWebChromeClient: WebChromeClient = object : WebChromeClient() {
        override fun onReceivedTitle(p0: WebView?, title: String?) {
            super.onReceivedTitle(p0, title)
            mTitleTextView?.setText(title)
        }
    }
    private val mWebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }

        override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
            //do you  work
            Log.i("Info", "BaseWebActivity onPageStarted")
        }
    };

    override fun getLayoutId(): Int {
        return R.layout.main_browser_activity
    }

    override fun initView() {
        mToolbar?.setTitleTextColor(Color.WHITE)
        mToolbar?.title = ""
        setSupportActionBar(mToolbar)
        supportActionBar?.let {
            // 设置返回键
            it.setDisplayHomeAsUpEnabled(true)
        }
    }

    override fun initData() {
        val content = intent.getStringExtra("input")
        content?.let {
            if (RegexUtils.isURL(it) || RegexUtils.isIP(it)) {
                currentUrl = it
            } else {
                if (RegexUtils.isMatch("^[a-zA-Z0-9-]+\\.[a-zA-Z]{2,}$", it)) {
                    // 如果符合格式且没有协议头，则添加 "https://"
                    if (!it.startsWith("http://") && !it.startsWith("https://")) {
                        currentUrl = "https://$it"
                    } else {
                        currentUrl = "https://cn.bing.com/search?q=$it&form=QBLH&sp=-1&lq=0"
                    }
                } else {
                    // search?q=vn&form=QBLH&sp=-1&lq=0&pq=&sc=10-0&qs=n&sk=&cvid=94420EE6C69F4046815C2440000041E9
                    currentUrl = "https://cn.bing.com/search?q=$it&form=QBLH&sp=-1&lq=0"
                }
            }
            mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(container!!, LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(com.just.agentweb.R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setWebLayout(WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK) //打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownUrl() //拦截找不到相关页面的Scheme
                .createAgentWeb()
                .ready()
                .go(currentUrl)
        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (mAgentWeb?.handleKeyEvent(keyCode, event) == true) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onPause() {
        mAgentWeb?.getWebLifeCycle()?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAgentWeb?.getWebLifeCycle()?.onDestroy()
    }
}
